<?php
require_once 'auth.php';
requireLogin();
$success = $quantity = $error = '';
// 处理入库操作
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $conn = dbConnect();
    $quantity = $_POST['quantity'];
    // 开启事务
    $conn->begin_transaction();
    try {
        $stmt = $conn->prepare('INSERT INTO stock_records (item_id, quantity, operation_type, operator_id) VALUES (?, ?, "in", ?)');
        $stmt->bind_param('iii', $_POST['item_id'], $_POST['quantity'], $_SESSION['user_id']);
        $stmt->execute();

        // 更新库存数量
        $updateStmt = $conn->prepare('UPDATE inventory SET quantity = quantity + ? WHERE id = ?');
        $updateStmt->bind_param('ii', $_POST['quantity'], $_POST['item_id']);
        $updateStmt->execute();

        // 记录操作日志
        $logStmt = $conn->prepare("INSERT INTO operation_logs (user_id, operation_type, target_id, details) VALUES (?, 'in', ?, ?)");
        $logDetails = '入库数量：' . $_POST['quantity'];
        $logStmt->bind_param('iis', $_SESSION['user_id'], $_POST['item_id'], $logDetails);
        $logStmt->execute();

        // 提交事务
        $conn->commit();
        $success = '入库成功';
        //header('Location: inventory.php');
        //exit;
    } catch (Exception $e) {
        // 回滚事务
        $conn->rollback();
        error_log('入库失败: ' . $e->getMessage()); // 添加日志记录
        $error = '入库失败，请联系管理员';
    }
}

// 获取物品列表
$conn = dbConnect();
$items = $conn->query('SELECT id, product_name FROM inventory');
?>
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>入库管理</title>
    <link rel="stylesheet" href="/dist/css/tabler.min.css">
</head>

<body class="layout-fluid layout-vertical">
    <?php include 'navbar.php'; ?>
    <div class="page">
        <div class="container-fluid">
            <div class="card mt-3">
                <div class="card-header">
                    <h3 class="card-title">货物入库</h3>
                </div>
                <div class="card-body">
                    <?php if (!empty($error)): ?>
                        <div class="alert alert-danger" role="alert">
                            <div class="alert-icon">
                                <!-- Download SVG icon from http://tabler.io/icons/icon/alert-circle -->
                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"
                                    viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
                                    stroke-linecap="round" stroke-linejoin="round"
                                    class="icon alert-icon icon-2">
                                    <path d="M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0" />
                                    <path d="M12 8v4" />
                                    <path d="M12 16h.01" />
                                </svg>
                            </div>
                            <?= htmlspecialchars($error) ?>
                        </div>
                    <?php endif; ?>
                    <?php if (!empty($success)): ?>
                        <div class="alert alert-success" role="alert">
                            <div class="alert-icon">
                                <!-- Download SVG icon from http://tabler.io/icons/icon/check -->
                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"
                                    viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
                                    stroke-linecap="round" stroke-linejoin="round"
                                    class="icon alert-icon icon-2">
                                    <path d="M5 12l5 5l10 -10" />
                                </svg>
                            </div>
                            <div>
                                <h4 class="alert-heading">Wow! Everything worked!</h4>
                                <div class="alert-description">
                                    <?= htmlspecialchars($success) ?>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                    <form method="post">
                        <div class="card-body">
                            <div class="mb-3">
                                <label class="form-label">选择物品</label>
                                <select name="item_id" class="form-select" required>
                                    <?php while ($item = $items->fetch_assoc()):
                                        $selected = ($item['id'] == $_POST['item_id']) ? 'selected' : '';
                                    ?>

                                        <option value="<?= $item['id'] ?>" <?= $selected ?>><?= htmlspecialchars($item['product_name']) ?></option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">入库数量</label>
                                <input type="number" name="quantity" class="form-control" min="1" value="<?= $quantity ?>" required>
                            </div>
                        </div>
                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary">提交入库</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <script src="/dist/js/tabler.min.js"></script>
</body>

</html>